import { ProForm } from '@ant-design/pro-components';
import { Button, Form, message, Space } from 'antd';
import { useContext, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import React from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import ProFormItemDynamic from '../ProFormItemDynamic';
import { ApiInfo, ApiType, FormType, TableRecord, ProTableContexteValue, EventFormType, Forms, FormInfo } from '../../utils/types';
import { dataSource } from '../../utils/dataSource';

import { initConfig } from './config';

const ProFormDynamic = (props: any) => {
  // 处理字段数据，该给默认值给默认值，该隐藏隐藏
  const getFormFields = (columns: any[]): any[] => {
    if (!columns || Object.keys(columns).length === 0) return [];

    columns.forEach((column: any) => {
      column.formFieldType = column.formFieldType ?? 'ProFormText'; // 默认赋formFieldType类型为ProFormText
      column.placeholder = column.placeholder ?? '请输入';
      column.tooltip = column.tooltip ?? '';
      column.value = column.value ?? '';
    });
    if (props.isTable) {
      return columns.filter((column: any) => {
        return !column.dataIndex.includes('table-'); // 过滤数据
      });
    } else {
      return [...columns];
    }
  };

  const baseFormRef = useRef<ProFormInstance>(); // 表单
  let [config, setConfig] = new Array();

  [config, setConfig] = useState<any>(initConfig);

  const dealFormData = async () => {
    const type: FormType = props.formType;
    switch (type) {
      case 'detail':
      case 'edit':
      case 'add': {
        // 详情和编辑都需要先查询出来
        const key = config.dataSource.keyInfo.key; // 主键
        let value = ''; // 主键值

        const currentTableRecord: TableRecord = props.currentTableRecord;
        if (!currentTableRecord || Object.keys(currentTableRecord).length === 0) {
          return {};
        }
        value = currentTableRecord.record[key];

        const apiType: ApiType = 'detail';
        const apiInfo: ApiInfo = config.dataSource.apiList[apiType];
        apiInfo.parameter[key] = value;
        const dataDetail: any = await dataSource(apiType, apiInfo, '');

        if (!dataDetail) return {};
        return dataDetail;
      }
      default:
        return {};
    }
  };

  const getDataSourceAndDeal = async () => {
    const dataDetail = await dealFormData();
    if (!dataDetail) return;
    baseFormRef.current?.setFieldsValue(dataDetail); // 更新表单数据
  };

  React.useEffect(() => {
    // 更新表单
    const newConfig = { ...config };

    newConfig.formType = props.formType;
    newConfig.currentTableRecord = props.currentTableRecord;
    newConfig.dataSource = props.dataSource;

    setConfig(newConfig);
    getDataSourceAndDeal();
  }, [props.formType, props.currentTableRecord]);

  React.useEffect(() => {
    // 更新表单
    getDataSourceAndDeal();
  }, []);

  const onFormSubmit = () => {
    const type: FormType = props.formType;

    switch (type) {
      case 'edit': {
        const apiType: ApiType = 'update'; // 修改
        const apiInfo: ApiInfo = config.dataSource.apiList[apiType];
        baseFormRef.current?.validateFieldsReturnFormatValue?.().then((values) => {
          apiInfo.body = values;

          dataSource(apiType, apiInfo, '修改成功');
        });
        break;
      }
      case 'add': {
        const apiType: ApiType = 'add'; // 保存
        const apiInfo: ApiInfo = config.dataSource.apiList[apiType];
        baseFormRef.current?.validateFieldsReturnFormatValue?.().then((values) => {
          apiInfo.body = values;

          dataSource(apiType, apiInfo, '新增成功');
        });
        break;
      }
    }
  };

  if (Object.keys(config).length === 0) {
    message.warn('没有配置表单。');
    return <></>;
  }

  return (
    <>
      <ProForm
        formRef={baseFormRef}
        labelCol={config.forms[props.formType]?.formConfig?.layout === 'inline' ? undefined : config.forms[props.formType]?.formConfig?.labelCol} // inline 模式下不能设置值，否则显示异常
        wrapperCol={config.forms[props.formType]?.formConfig?.layout === 'inline' ? undefined : config.forms[props.formType]?.formConfig?.wrapperCol} // inline 模式下不能设置值，否则显示异常
        grid={config.forms[props.formType]?.formConfig?.grid}
        layout={config.forms[props.formType]?.formConfig?.layout}
        readonly={config.forms[props.formType]?.formConfig?.readonly}
        size={config.forms[props.formType]?.formConfig?.size}
        submitter={{
          // 完全自定义整个区域
          render: (formProps: any, doms: any) => {
            return [
              config.forms[props.formType]?.formConfig?.showReset || config.forms[props.formType]?.formConfig?.showSubmit ? (
                <Form.Item
                  wrapperCol={config.forms[props.formType]?.formConfig?.layout === 'horizontal' ? config.forms[props.formType]?.formConfig?.submitWrapperCol : undefined}
                  key="submit"
                >
                  <Space>
                    {config.forms[props.formType]?.formConfig?.showReset ? (
                      <Button type="default" key="rest" onClick={() => formProps.reset()}>
                        {config.forms[props.formType]?.formConfig?.resetText}
                      </Button>
                    ) : null}

                    {config.forms[props.formType]?.formConfig?.showSubmit ? (
                      <Button type="primary" onClick={() => formProps.submit()}>
                        {config.forms[props.formType]?.formConfig?.submitText}
                      </Button>
                    ) : null}
                  </Space>
                </Form.Item>
              ) : null,
            ];
          },
          onSubmit: () => {
            onFormSubmit();
          },
        }}
        onValuesChange={(_: any, values: any) => {}}
      >
        {config.forms[props.formType]?.formFields?.map((formFieldInfo: any, index: number) => {
          return <ProFormItemDynamic formFieldInfo={formFieldInfo} key={index} />;
        })}
      </ProForm>
    </>
  );
};
ProFormDynamic.propTypes = {
  config: PropTypes.object,
  formType: PropTypes.string,

  isTable: PropTypes.bool, // 是否表格表单
  currentTableRecord: PropTypes.object,
};
export default ProFormDynamic;
// export default ProFormDynamic;
